﻿using Newtonsoft.Json;
using System;

namespace Kz.Telegram.Bot.Infrastructure.Extensions
{
    /// <summary>
    /// JSON 序列化拓展
    /// </summary>
    public static class SerializeExtenisons
    {
        /// <summary>
        /// 序列化JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson<T>(this T obj) where T : class
        {
            try
            {
                return JsonConvert.SerializeObject(obj);
            }
            catch (Exception)
            {
                return "SerializeObject ERROR";
            }
        }

        /// <summary>
        /// JSON反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T ToObj<T>(this string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            catch (Exception)
            {
                return default;
            }
        }

        /// <summary>
        /// JSON反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T ToObj<T>(this object jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonStr.ToString());
            }
            catch (Exception)
            {
                return default;
            }
        }

    }
}